
import redis
import requests
import json
from settings import  SERVER_URL,  REDIS_PORT, REDIS_DB, REDIS_PASSWORD, \
      REDIS_TALK_DATA_PREFIX, REDIS_HOST


redis_client = redis.Redis(
                    host=REDIS_HOST,
                    port=REDIS_PORT,
                    db=REDIS_DB,
                    password=REDIS_PASSWORD,
                    decode_responses=True,
                    socket_timeout=2,
                )


def is_sending_sms(text: str):
    url = f"{SERVER_URL}/recognition"
    params = {"text": text}
    response = requests.get(url, params=params)
    return response.json()


def get_chat_data(device_phone:str,called_phone:str)-> list:
    key = f"chat_message:{device_phone}_{called_phone}"
    return redis_client.get(key)

def store_chat_data(session_id:str,sender:str,receiver:str,content:str):
    url = f"{SERVER_URL}/qw/chat/message"
    data = {
        "session_id": session_id,
        "sender": sender,
        "receiver": receiver,
        "content": content
    }
    response = requests.post(url, json=data)
    return response.json()

def get_customer_data(device_phone: str) -> dict:
    """获取客户数据
    
    Args:
        device_phone: 设备手机号
        
    Returns:
        dict: 客户数据字典，如果Redis中没有数据则返回默认值
        
    Raises:
        Exception: 如果Redis连接失败或其他错误
    """
    try:
        data = redis_client.get(REDIS_TALK_DATA_PREFIX+device_phone)
        if data is None:
            # 如果没有数据，返回默认值
            # print(f"警告: Redis中未找到设备 {device_phone} 的客户数据，使用默认值,{REDIS_TALK_DATA_PREFIX+device_phone}")
            return {
                "customer_name": "客户",
                "phone": ""
            }
        data = json.loads(data)
        return data
    except json.JSONDecodeError as e:
        print(f"解析客户数据JSON失败: {e}")
        # 返回默认值
        return {
            "customer_name": "客户",
            "phone": ""
        }
    except Exception as e:
        print(f"获取客户数据失败: {e}")
        raise

def get_talking_status(device_phone: str):
    value = redis_client.get(f"app_talk_status:{device_phone}")
    if  value is None:
        return None
    return value.split("_")[1]

def send_sms(called_phone:str,device_phone:str):
    status:str = get_sms_phone(device_phone)
    if status is None:
        set_sms_phone(device_phone, called_phone,"sending")
        print("正在发送短信...")
        return True
    # 如果已经发送了短信，则返回
    if status.split("_")[0] == called_phone:
        print("已经发送了短信，请勿重复发送")
        return False
    set_sms_phone(device_phone, called_phone,"sending")
    print("正在发送短信...")
    return True


def set_sms_phone(device_phone,phone,status):
    value = f"{phone}_{status}"
    redis_client.set(f"sms_phone:{device_phone}",value,ex=60*60*12)


def set_sms_content(device_phone,content):
    redis_client.set(f"sms_content:{device_phone}",content,ex=60*60*12)




def set_guaduan_phone(device_phone,status : str):
    redis_client.set(f"call_talk_is_ened:{device_phone}",status,ex=60)

def get_sms_phone(device_phone):
    return redis_client.get(f"sms_phone:{device_phone}")

def get_redis_value(key):
    return redis_client.get(key)

def set_redis_value(key,value):
    redis_client.set(key,value,ex=60*60*12)

def publish_redis(channel,message):
    redis_client.publish(channel,message)

# if __name__ == '__main__':
#     print(get_redis_value("app_talk_status:12345678901"))